using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using PropertyExpression.Common;
using PropertyExpression.ControllableQuery;

namespace LibraryCatalog
{
    public static class QExecuter
    {
        public static List<T> List<T>(this IQuery<Type<T>> it)
        {
            return it.Result().ToList();
        }

        public static IEnumerable<T> Result<T>(this IQuery<Type<T>> it)
        {
            using (var connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.SetQuery(it);
                    using (var sqlDataReader = command.ExecuteReader())
                        while (sqlDataReader.Read())
                            yield return sqlDataReader.Materialize<T>();
                }
            }
        }

        public static int Execute(this INonQuery it)
        {
            using (var connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.SetQuery(it);
                    return command.ExecuteNonQuery();
                }
            }
        }

        internal static string ConnectionString
        {
            get { return @"Data Source=(local)\SQL2012;Initial Catalog=LibraryCatalog;Integrated Security=True"; }
        }
    }
}